package cn.shop.cloud.web.mq;

import cn.shop.cloud.service.IOrderInfoService;
import cn.shop.cloud.service.ISeckillGoodService;
import cn.shop.cloud.web.controller.OrderInfoController;
import cn.shop.cloud.web.msg.SeckillCodeMsg;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @program: work
 * @ClassName OrderMQListener
 * @description:
 * @author: 李尧坤
 * @create: 2025−01-10 15:06
 * @Version 1.0
 **/

@Component
public class OrderMQListener {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ISeckillGoodService seckillGoodService;

    //处理订单消息的队列  @Payload 把MQ中的二进制数据通过反序列化拿到 转成 OrderMessage

    /**
     *   异步下单
     * @param orderMessage  传递的信息  uuid  userId  seckillId
     * @param deliveryTag  消息签收的唯一标识
     * @param channel   信道
     */
    @RabbitListener(queuesToDeclare =@Queue(name = MQConstants.ORDER_PEDDING_QUEUE))
    public void handlerOrderPeddingQueue(
            @Payload OrderMessage orderMessage,
            @Header(AmqpHeaders.DELIVERY_TAG)Long deliveryTag,
            Channel channel){

        Map<String, Object> param = new HashMap<>();
        param.put("uuid",orderMessage.getUuid());
        param.put("seckillId",orderMessage.getSeckillId());

        try{
            //获取订单编号
            String orderNo = orderInfoService.
                    doSeckill(orderMessage.getUserId(),orderMessage.getSeckillId());
            param.put("orderNo",orderNo);
            param.put("msg","亲，下单成功了请尽快去支付.....");
            //需要进行 ack
            rabbitTemplate.convertAndSend(
                    MQConstants.ORDER_RESULT_EXCHANGE,
                    MQConstants.ORDER_RESULT_SUCCESS_KEY,
                    param
            );



        }catch (Exception ex){
            ex.printStackTrace();
            param.put("msg","下单失败了...");
            param.put("code", SeckillCodeMsg.PRODUCT_CODE_MSG_ERROR.getCode());
        }finally {
            try {
                //消息签收
                channel.basicAck(deliveryTag,false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


    }

    //处理下单失败的情况
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = MQConstants.ORDER_RESULT_FAIL_QUEUE),
                    exchange = @Exchange(name = MQConstants.ORDER_RESULT_EXCHANGE,type = "topic"),
                    key = MQConstants.ORDER_RESULT_FAIL_KEY)
    )
    public void handlerOrderFailQueue(@Payload Map<String, Object> param,
                                      @Header(AmqpHeaders.DELIVERY_TAG)Long deliveryTag,
                                      Channel channel ){
        //获取场次id
        Long seckillId = (Long) param.get("seckillId");

        //需要进行库存回补
        try{
            seckillGoodService.syncRedisStcokCount(seckillId);
        }catch (Exception ex){
            ex.printStackTrace();

        }finally {
            try {
                //消息签收
                channel.basicAck(deliveryTag,false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }



    }

    //声明  但是不进行监听  下单成功了
    @Bean
    public org.springframework.amqp.core.Queue orderSuccessDelayQueue(){
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange",MQConstants.DELAY_EXCHANGE); //死信交换机
        arguments.put("x-dead-letter-routing-key",MQConstants.ORDER_DELAY_KEY);// 死信 路由键
        arguments.put("x-message-ttl",10*60*1000);//存活时间

        //  public Queue(String name,   队列名
        //  boolean durable,   是否持久化
        //  boolean exclusive, 是否排它
        //  boolean autoDelete,   是否自定删除
        //  Map<String, Object> arguments) {  相关配置参数

        return  new org.springframework.amqp.core.Queue(
                MQConstants.ORDER_RESULT_SUCCESS_DELAY_QUEUE,
                true,
                false,
                false,
                arguments
        );
    }

    @Bean
    public Binding badingla(org.springframework.amqp.core.Queue orderSuccessDelayQueue){ //必须和128行的方法名一致，否则绑定不上
        return BindingBuilder.
                bind(orderSuccessDelayQueue).
                to(new TopicExchange(MQConstants.ORDER_RESULT_EXCHANGE)).
                with(MQConstants.ORDER_RESULT_SUCCESS_KEY);
    }

    //超时没有支付
    @RabbitListener(
            bindings = @QueueBinding(value = @Queue(name = MQConstants.ORDER_TIMEOUT_QUEUE),
                    exchange = @Exchange(name = MQConstants.DELAY_EXCHANGE,type = "topic"),
                    key = MQConstants.ORDER_DELAY_KEY)
    )
    public void handlerTimeQueue(@Payload Map<String, Object> param,
                                 @Header(AmqpHeaders.DELIVERY_TAG)Long deliveryTag,
                                 Channel channel ){

        try{
            //获取场次id
            Long seckillId = (Long) param.get("seckillId");
            //订单编号
            String orderNo = (String) param.get("orderNo");
            //判断一下订单状态 取消订单
            orderInfoService.cancelOrder(seckillId,orderNo);

        }catch (Exception ex){
            ex.printStackTrace();
            //使用短信  或者  邮件功能  通知运维

        }finally {
            try {
                //消息签收
                channel.basicAck(deliveryTag,false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }



    }




    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue,//匿名队列
                    exchange = @Exchange(name = MQConstants.SECKILL_OVER_SIGN_PUBSUB_EX,type = "fanout")
            )
    )
    public void handlerCancelSign(Long seckillId,
                                  @Header(AmqpHeaders.DELIVERY_TAG)Long deliveryTag,
                                  Channel channel){

        System.out.println("取消本地标识.....");
        OrderInfoController.isOverSignMap.put(seckillId,false);

    }





}
